package com.jprocms.module.cms.service.tplinclude;

import cn.hutool.core.collection.CollUtil;
import com.jpro.framework.common.pojo.PageResult;
import com.jpro.framework.common.util.object.BeanUtils;
import com.jprocms.module.cms.controller.admin.tplinclude.vo.TplIncludePageReqVO;
import com.jprocms.module.cms.controller.admin.tplinclude.vo.TplIncludeSaveReqVO;
import com.jprocms.module.cms.dal.dataobject.tplinclude.TplIncludeDO;
import com.jprocms.module.cms.dal.mysql.tplinclude.TplIncludeMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.TPL_INCLUDE_NOT_EXISTS;

/**
 * 模板包含页面 Service 实现类
 *
 * @author jprocms
 */
@Service
@Validated
public class TplIncludeServiceImpl implements TplIncludeService {

    @Resource
    private TplIncludeMapper tplIncludeMapper;

    @Override
    public Long createTplInclude(TplIncludeSaveReqVO createReqVO) {
        // 插入
        TplIncludeDO tplInclude = BeanUtils.toBean(createReqVO, TplIncludeDO.class);
        tplIncludeMapper.insert(tplInclude);
        // 返回
        return tplInclude.getId();
    }

    @Override
    public void updateTplInclude(TplIncludeSaveReqVO updateReqVO) {
        // 校验存在
        validateTplIncludeExists(updateReqVO.getId());
        // 更新
        TplIncludeDO updateObj = BeanUtils.toBean(updateReqVO, TplIncludeDO.class);
        tplIncludeMapper.updateById(updateObj);
    }

    @Override
    public void deleteTplInclude(Long id) {
        // 校验存在
        validateTplIncludeExists(id);
        // 删除
        tplIncludeMapper.deleteById(id);
    }

    private void validateTplIncludeExists(Long id) {
        if (tplIncludeMapper.selectById(id) == null) {
            throw exception(TPL_INCLUDE_NOT_EXISTS);
        }
    }

    @Override
    public TplIncludeDO getTplInclude(Long id) {
        return tplIncludeMapper.selectById(id);
    }

    @Override
    public TplIncludeDO getTplInclude(String tplPath, Long siteId) {
        final List<TplIncludeDO> tplIncludeDOS = tplIncludeMapper.selectList(TplIncludeDO::getTplPath, tplPath, TplIncludeDO::getSiteId, siteId);
        if (CollUtil.isEmpty(tplIncludeDOS)) {
            return null;
        }
        return tplIncludeDOS.get(0);
    }

    @Override
    public PageResult<TplIncludeDO> getTplIncludePage(TplIncludePageReqVO pageReqVO) {
        return tplIncludeMapper.selectPage(pageReqVO);
    }

    @Override
    public List<TplIncludeDO> getTplIncludeList(Long siteId) {
        return tplIncludeMapper.selectList(TplIncludeDO::getSiteId, siteId, TplIncludeDO::getIncludePage, true);
    }
}